<template>
  <div>
    <h1 class="page-title">药品防伪验证</h1>
    
    <a-row :gutter="24">
      <a-col :xs="24" :md="12">
        <a-card class="verification-card">
          <template #title>
            <div class="card-title">
              <safety-certificate-outlined style="font-size: 20px; color: #1890ff" />
              <span>RFID防伪验证</span>
            </div>
          </template>
          <div class="verification-form">
            <a-form layout="vertical">
              <a-form-item label="RFID ID" required>
                <a-input-search
                  v-model:value="rfidId"
                  placeholder="请输入16位RFID标识符"
                  @search="handleVerify"
                  enter-button="验证"
                  size="large"
                />
              </a-form-item>
              <a-form-item label="验证码 (选填)">
                <a-input
                  v-model:value="verificationCode"
                  placeholder="输入验证码提高防伪验证准确性"
                />
              </a-form-item>
              <a-form-item>
                <a-button
                  type="primary"
                  block
                  size="large"
                  :loading="verifying"
                  @click="handleVerify"
                >
                  进行验证
                </a-button>
              </a-form-item>
            </a-form>
          </div>
        </a-card>
      </a-col>
      
      <a-col :xs="24" :md="12">
        <a-card v-if="result" class="result-card">
          <template #title>
            <div class="card-title">
              <span>验证结果</span>
              <a-tag :color="result.is_genuine ? 'success' : 'error'">
                {{ result.is_genuine ? '验证通过' : '验证失败' }}
              </a-tag>
            </div>
          </template>
          
          <div v-if="result.is_genuine" class="verification-result genuine">
            <div class="result-icon">
              <check-circle-filled />
            </div>
            <div class="result-message">
              <h3>此药品是正品</h3>
              <p>{{ result.message }}</p>
              <p class="time-info">验证时间: {{ elapsedTime }}ms</p>
            </div>
            
            <a-divider />
            
            <div v-if="result.medicine_info" class="medicine-info">
              <h3>药品详情</h3>
              <a-descriptions bordered :column="1">
                <a-descriptions-item label="RFID ID">
                  <a-tag color="blue">{{ result.medicine_info.rfid_id }}</a-tag>
                </a-descriptions-item>
                <a-descriptions-item label="药品名称">
                  {{ result.medicine_info.name }}
                </a-descriptions-item>
                <a-descriptions-item label="规格">
                  {{ result.medicine_info.spec }}
                </a-descriptions-item>
                <a-descriptions-item label="生产厂家">
                  {{ result.medicine_info.manufacturer }}
                </a-descriptions-item>
                <a-descriptions-item label="生产批次">
                  <a-tag color="blue">{{ result.medicine_info.batch }}</a-tag>
                </a-descriptions-item>
                <a-descriptions-item label="生产日期">
                  {{ formatDate(result.medicine_info.production_date) }}
                </a-descriptions-item>
                <a-descriptions-item label="有效期至">
                  {{ formatDate(result.medicine_info.expiry_date) }}
                  <a-tag v-if="isExpired(result.medicine_info.expiry_date)" color="red">已过期</a-tag>
                  <a-tag v-else color="green">有效期内</a-tag>
                </a-descriptions-item>
              </a-descriptions>
              
              <div class="action-buttons">
                <a-button type="primary" @click="viewTrace">
                  <template #icon><apartment-outlined /></template>
                  查看完整追溯
                </a-button>
              </div>
            </div>
          </div>
          
          <div v-else class="verification-result fake">
            <div class="result-icon">
              <close-circle-filled />
            </div>
            <div class="result-message">
              <h3>警告：此药品可能是假冒产品！</h3>
              <p>{{ result.message }}</p>
              <p class="time-info">验证时间: {{ elapsedTime }}ms</p>
            </div>
            
            <a-divider />
            
            <div class="alert-info">
              <a-alert
                type="error"
                message="可能的风险"
                description="假冒药品可能含有有害物质，严重威胁健康安全。请勿使用可疑药品，并立即向相关部门举报。"
                show-icon
              />
              
              <div class="action-buttons">
                <a-button danger>
                  <template #icon><warning-outlined /></template>
                  举报假冒产品
                </a-button>
              </div>
            </div>
          </div>
        </a-card>
        
        <a-card v-else class="help-card">
          <template #title>
            <div class="card-title">
              <info-circle-outlined style="font-size: 20px; color: #1890ff" />
              <span>防伪验证指南</span>
            </div>
          </template>
          
          <div class="help-content">
            <a-timeline>
              <a-timeline-item>
                <div class="step-content">
                  <h3>第一步：找到RFID标识</h3>
                  <p>每个药品包装上都有一个16位数字的RFID标识符，通常位于包装侧面或底部。</p>
                </div>
              </a-timeline-item>
              <a-timeline-item>
                <div class="step-content">
                  <h3>第二步：输入RFID ID</h3>
                  <p>在左侧输入框中输入16位RFID标识符，可选择性地输入验证码以提高验证准确性。</p>
                </div>
              </a-timeline-item>
              <a-timeline-item>
                <div class="step-content">
                  <h3>第三步：验证真伪</h3>
                  <p>点击"验证"按钮，系统将在1秒内完成验证并显示结果。</p>
                </div>
              </a-timeline-item>
              <a-timeline-item>
                <div class="step-content">
                  <h3>第四步：查看详情</h3>
                  <p>验证通过后，可查看药品详细信息和完整追溯记录，确保药品来源可靠。</p>
                </div>
              </a-timeline-item>
            </a-timeline>
            
            <a-alert 
              type="info" 
              message="安全提示" 
              description="本系统通过区块链和加密技术保障数据安全，验证结果准确率达到100%。若发现假冒药品，请立即向有关部门举报。"
              show-icon
            />
          </div>
        </a-card>
      </a-col>
    </a-row>
    
    <!-- Verification History -->
    <a-card title="最近验证记录" class="history-card mt-16">
      <a-table
        :dataSource="verificationHistory"
        :columns="columns"
        :pagination="{ pageSize: 5 }"
        size="middle"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'result'">
            <a-tag :color="record.is_genuine ? 'success' : 'error'">
              {{ record.is_genuine ? '验证通过' : '验证失败' }}
            </a-tag>
          </template>
          <template v-if="column.key === 'action'">
            <a-button type="link" size="small" @click="repeatVerify(record)">
              重新验证
            </a-button>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import moment from 'moment'
import api from '@/services/api'
import {
  SafetyCertificateOutlined,
  CheckCircleFilled,
  CloseCircleFilled,
  ApartmentOutlined,
  WarningOutlined,
  InfoCircleOutlined
} from '@ant-design/icons-vue'

// Types
interface VerificationResult {
  is_genuine: boolean
  message: string
  verification_time: number
  medicine_info?: any
}

interface VerificationRecord {
  key: number
  rfid_id: string
  time: string
  is_genuine: boolean
  verification_time: number
}

// State
const router = useRouter()
const rfidId = ref('')
const verificationCode = ref('')
const verifying = ref(false)
const result = ref<VerificationResult | null>(null)
const elapsedTime = ref(0)
const verificationHistory = ref<VerificationRecord[]>([])

// Table columns
const columns = [
  {
    title: 'RFID ID',
    dataIndex: 'rfid_id',
    key: 'rfid_id',
  },
  {
    title: '验证时间',
    dataIndex: 'time',
    key: 'time',
  },
  {
    title: '验证结果',
    dataIndex: 'is_genuine',
    key: 'result',
  },
  {
    title: '验证用时',
    dataIndex: 'verification_time',
    key: 'speed',
    render: (time: number) => `${time}ms`
  },
  {
    title: '操作',
    key: 'action',
  }
]

// Methods
const handleVerify = async () => {
  if (!rfidId.value || rfidId.value.length !== 16) {
    message.warning('请输入16位RFID标识符')
    return
  }

  verifying.value = true
  const startTime = Date.now()
  
  try {
    const response = await api.verifyMedicine({
      rfid_id: rfidId.value,
      verification_code: verificationCode.value || null
    })
    
    const verificationResult = response.data
    result.value = verificationResult
    
    // Calculate elapsed time
    const elapsed = Date.now() - startTime
    elapsedTime.value = elapsed
    
    // Record to history
    const historyItem: VerificationRecord = {
      key: Date.now(),
      rfid_id: rfidId.value,
      time: moment().format('YYYY-MM-DD HH:mm:ss'),
      is_genuine: verificationResult.is_genuine,
      verification_time: elapsed
    }
    
    verificationHistory.value.unshift(historyItem)
    
    // Keep only the last 10 records
    if (verificationHistory.value.length > 10) {
      verificationHistory.value = verificationHistory.value.slice(0, 10)
    }
    
    // Save to localStorage
    saveVerificationHistory()
    
    // Check performance requirement
    if (elapsed > 1000) {
      message.warning(`验证完成，但用时 ${elapsed}ms 超过了预期的1秒`)
    }
    
  } catch (error) {
    console.error('Failed to verify medicine:', error)
    message.error('验证失败，请稍后再试')
  } finally {
    verifying.value = false
  }
}

const viewTrace = () => {
  if (result.value && result.value.medicine_info) {
    router.push({
      path: '/trace',
      query: { rfid: result.value.medicine_info.rfid_id }
    })
  }
}

const repeatVerify = (record: VerificationRecord) => {
  rfidId.value = record.rfid_id
  verificationCode.value = ''
  handleVerify()
}

const formatDate = (dateStr: string): string => {
  return moment(dateStr, 'YYYYMMDD').format('YYYY-MM-DD')
}

const isExpired = (dateStr: string): boolean => {
  return moment(dateStr, 'YYYYMMDD').isBefore(moment(), 'day')
}

const saveVerificationHistory = () => {
  localStorage.setItem('verificationHistory', JSON.stringify(verificationHistory.value))
}

const loadVerificationHistory = () => {
  const history = localStorage.getItem('verificationHistory')
  if (history) {
    try {
      verificationHistory.value = JSON.parse(history)
    } catch (e) {
      console.error('Failed to parse verification history from localStorage', e)
    }
  }
}

// Lifecycle hooks
onMounted(() => {
  loadVerificationHistory()
})
</script>

<style scoped>
.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.verification-card,
.result-card,
.help-card {
  height: 100%;
}

.verification-form {
  padding: 16px 0;
}

.verification-result {
  padding: 16px 0;
}

.genuine .result-icon {
  display: flex;
  justify-content: center;
  margin-bottom: 16px;
}

.genuine .result-icon :deep(svg) {
  font-size: 64px;
  color: #52c41a;
}

.fake .result-icon {
  display: flex;
  justify-content: center;
  margin-bottom: 16px;
}

.fake .result-icon :deep(svg) {
  font-size: 64px;
  color: #f5222d;
}

.result-message {
  text-align: center;
  margin-bottom: 16px;
}

.result-message h3 {
  margin-bottom: 8px;
  font-size: 18px;
}

.time-info {
  color: #999;
  font-size: 12px;
}

.medicine-info {
  margin-top: 16px;
}

.medicine-info h3 {
  margin-bottom: 16px;
}

.alert-info {
  margin-top: 16px;
}

.action-buttons {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

.help-content {
  padding: 16px 0;
}

.step-content {
  margin-bottom: 16px;
}

.step-content h3 {
  margin-bottom: 8px;
  font-size: 16px;
  color: #1890ff;
}

.history-card {
  margin-top: 24px;
}
</style> 